package com.weiweiqin.controller.home;

import com.weiweiqin.constants.PropertyConfig;
import com.weiweiqin.model.JssdkAccess;
import com.weiweiqin.service.JssdkAccessService;
import com.weiweiqin.utils.CommonUtil;
import com.weiweiqin.utils.GsonUtils;
import com.weiweiqin.utils.HttpClientUtil;
import com.weiweiqin.utils.Sign;
import com.weiweiqin.vo.common.Result;
import com.weiweiqin.weixin.pojo.JsapiTicket;
import com.weiweiqin.weixin.pojo.Token;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("front/common")
public class FCommonController {

	private static final Logger logger = LoggerFactory.getLogger(FCommonController.class);

	private static String APPID = "";
	private static String SECRET = "";

	static {
		APPID = PropertyConfig.getInstance().getProperty("APPID");
		SECRET = PropertyConfig.getInstance().getProperty("SECRET");
	}

	@Autowired
	private JssdkAccessService jssdkAccessService;

	@RequestMapping(value = "/getJssdk.do", method = { RequestMethod.GET})
	@ResponseBody
	public String getJssdk(String url,HttpSession session) {
		Result result = new Result();
		JssdkAccess token = getToken();
		if(null != token){
			if(StringUtils.isNotEmpty(token.getJsapiTicket())) {
				Map<String, String> sign = Sign.sign(token.getJsapiTicket(), url);
				sign.put("appId",APPID);
				sign.remove("jsapi_ticket");
				result.setObj(sign);
				result.setResult(true);
			//重新获取ticket
			}else {
				JsapiTicket jsapiTicket = getJsapiTicket(token.getAccessToken());
				if(null != jsapiTicket){
					token.setJsapiTicket(jsapiTicket.getTicket());
					jssdkAccessService.update(token);
					Map<String, String> sign = Sign.sign(jsapiTicket.getTicket(), url);
					sign.put("appId",APPID);
					sign.remove("jsapi_ticket");
					result.setObj(sign);
					result.setResult(true);
				}else {
					logger.error("------------------------获取ticket失败");
				}
			}
        }
		return result.toJson();
	}

	private JsapiTicket getJsapiTicket(String token) {
		JsapiTicket jsapiTicket;
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
		String s = HttpClientUtil.httpGetRequest(url);
		logger.info("Jsapi_Ticket:" + s);
		jsapiTicket = GsonUtils.convertObj(s, JsapiTicket.class);
		return jsapiTicket;
	}

	private JssdkAccess getToken() {
		Token token = null;
		JssdkAccess jssdkAccess = jssdkAccessService.get(1);
		long now = new Date().getTime();
		//缓存时间1小时，没有缓存或者缓存过期，重新获取tocken
		if(null == jssdkAccess || (now-jssdkAccess.getUpdateDate().getTime())>3600000) {
			token = CommonUtil.getToken(APPID, SECRET);
			if (token != null) {
				String accessTocken = token.getAccessToken();
				if(null == jssdkAccess) {
					jssdkAccess = new JssdkAccess();
				}
				jssdkAccess.setAccessToken(accessTocken);
				jssdkAccess.setJsapiTicket("");
				jssdkAccess.setUpdateDate(new Date());
				if(null == jssdkAccess.getId()) {
					jssdkAccessService.save(jssdkAccess);
				}else {
					jssdkAccessService.update(jssdkAccess);
				}

			}else {
				logger.error("---------------------------------获取tocken失败");
			}
		}else{
			//从数据库获取
			token = new Token();
			token.setAccessToken(jssdkAccess.getAccessToken());
		}
		logger.info("WX_Token:" + token.getAccessToken());
		return jssdkAccess;
	}

}
